package com.ydkj.a37e_mall.Resource.Utils;

import android.util.Base64;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.security.KeyFactory;
import java.security.NoSuchAlgorithmException;
import java.security.PublicKey;
import java.security.spec.X509EncodedKeySpec;

import javax.crypto.Cipher;

/**
 * @author alun (http://alunblog.duapp.com)
 * @version 1.0
 * @created 2013-5-17
 */
public class Rsa {
    private static final String RSA_PUBLICE =
            "MIICIjANBgkqhkiG9w0BAQEFAAOCAg8AMIICCgKCAgEAsRwOpbpqxaBxO7Uj+rg9" +
                    "t1QZAGy5+b2TTy5hLYTmgjmfNzFEyrBGPUl/CceVUnlOG8YWMSjacBQ/v7+2DQW6" +
                    "Gmp8vVaMTsVHuMA3nM1DORuKqSrBTdpOLfQ1zdQHCTO4RggsSlyLKPBxK2WE1kQX" +
                    "+x060EapBIMj0VXHFzDGmW7lzrOFf47CBNFnwPzcDNvKnuqvQiv62fb++HTkB6B2" +
                    "FOjeNw5K0KZYIKoATXdxIMLyw8169nyLtehKeCrlbVv/xFdKcotx8FjJPRdTr30W" +
                    "l+EEK2oSIpnGYfj7wf25G6askg0cc3Eks/nmaRdFIDPfF6gd6mWioZjj22MGYiQ2" +
                    "lLWNhoh+J2ZRPouwREC+ZHpS1ncyFFE+If5jnUeMrzXjjI0Fb8Bjyc39PYpi+eeX" +
                    "leWm4NDKmEsLxuKAsIS94ykR392munXVZhh7oC/1cQ/buFowFOfwqnhLnBZGMwyQ" +
                    "6LLZQbKJl84jPOMy76nP0DEBvR60hz6MB1M4qLt8PxjvHJ9xf4WMxwe9fDqMevo+" +
                    "J9nbgE0l3rA2G8dWxMzrLyN2miWDI1unaUreXBqk+L9Q9ljGsl3PdLFa08JWSwI2" +
                    "o6qqL4vUtUMdF3trz/2niuMYAM+7S2E9ZST0Q1cgWfyjY/rjbTAyjpTZiJDg5bT0" +
                    "7jT7iPEUjLBzlh7JaFR958cCAwEAAQ==";

    private static final String ALGORITHM = "RSA";

    /**
     * 得到公钥
     *
     * @param algorithm
     * @param bysKey
     * @return
     */
    private static PublicKey getPublicKeyFromX509(String algorithm,
                                                  String bysKey) throws NoSuchAlgorithmException, Exception {
        byte[] decodedKey = Base64.decode(bysKey, Base64.DEFAULT);
        X509EncodedKeySpec x509 = new X509EncodedKeySpec(decodedKey);

        KeyFactory keyFactory = KeyFactory.getInstance(algorithm);
        return keyFactory.generatePublic(x509);
    }

    /**
     * 使用公钥加密
     *
     * @param content
     * @param key
     * @return
     */
    public static String encryptByPublic(String content) {
        try {
            PublicKey pubkey = getPublicKeyFromX509(ALGORITHM, RSA_PUBLICE);

            Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
            cipher.init(Cipher.ENCRYPT_MODE, pubkey);

            byte plaintext[] = content.getBytes("UTF-8");
            byte[] output = cipher.doFinal(plaintext);

            String s = new String(Base64.encode(output, Base64.DEFAULT));

            return s;

        } catch (Exception e) {
            return "error";
        }
    }

    /**
     * 使用公钥解密
     *
     * @param content 密文
     * @param key     商户私钥
     * @return 解密后的字符串
     */
    public static String decryptByPublic(String content) {
        try {
            PublicKey pubkey = getPublicKeyFromX509(ALGORITHM, RSA_PUBLICE);
            Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
            cipher.init(Cipher.DECRYPT_MODE, pubkey);
            InputStream ins = new ByteArrayInputStream(Base64.decode(content, Base64.DEFAULT));
            ByteArrayOutputStream writer = new ByteArrayOutputStream();
            byte[] buf = new byte[128];
            int bufl;
            while ((bufl = ins.read(buf)) != -1) {
                byte[] block = null;
                if (buf.length == bufl) {
                    block = buf;
                } else {
                    block = new byte[bufl];
                    for (int i = 0; i < bufl; i++) {
                        block[i] = buf[i];
                    }
                }
                writer.write(cipher.doFinal(block));
            }
            return new String(writer.toByteArray(), "utf-8");
        } catch (Exception e) {
            return null;
        }
    }

}